package com.frxuexi.mymvi

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AppsViewModel @Inject constructor(private val appsRepository: AppsRepository):ViewModel() {
    //存放和管理意图的通道
    val channel = Channel<AppsIntent>()

    //用于更新UI的状态
    private var _state= MutableStateFlow<AppsState>(AppsState.onLoading)
    val state:StateFlow<AppsState>
        get() = _state

    //初始代码块
    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                when(it){
                    is AppsIntent.getApps->{
                        getApps()
                    }

                    else -> {}
                }
            }
        }
    }

    fun getApps(){
        viewModelScope.launch {
            appsRepository.getApps()
                .flowOn(Dispatchers.IO)//指定在子线程执行
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.code==0){
                        _state.value=AppsState.onSuccess(it.data)
                    }else{
                        _state.value=AppsState.onError(it.msg)
                    }
                }
        }
    }
}